﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using Reactor.Messages.Replies.Diagnostics;
using Reactor.Messaging;

namespace Reactor.MiniManager.ViewModels
{
    public class EndpointDestinationViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="EndpointDestinationViewModel"/> class.
        /// </summary>
        /// <param name="typedDestinationName">Name of the typed destination.</param>
        public EndpointDestinationViewModel(string typedDestinationName)
        {
            if(string.IsNullOrEmpty(typedDestinationName)) throw new ArgumentNullException("typedDestinationName");

            MessageTypeNames = new ObservableCollection<string>();
            Destination = Messaging.Destination.FromTypedDestinationName(typedDestinationName);
        }

        public ObservableCollection<string> MessageTypeNames { get; set; }

        public string Name
        {
            get
            {
                return Destination.DestinationName;
            }
        }

        public bool IsQueue
        {
            get
            {
                return Destination.GetTypedDestinationName().StartsWith(Messaging.Destination.TypedQueuePrefix);
            }
        }

        public IDestination Destination { get; private set; }

        public void Refresh(EndpointDiagnosticsResponse.DestinationToMessageTypesMap map)
        {
            if(map.DestinationName != Destination.GetTypedDestinationName()) return; //Don't process if it's not ours

            MessageTypeNames.Clear();

            // Add any that were not previously here
            foreach (var messageTypeName in map.MessageTypeNames.Where(messageTypeName => !MessageTypeNames.Contains(messageTypeName)))
                MessageTypeNames.Add(messageTypeName);
        }
    }
}
